package hz.mobileproject.pda.network;

import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by hasee on 2017/10/30.
 * 同步下载图片
 */
public class PhotoDownLoadNetWork {

    private static final String TAG = PhotoDownLoadNetWork.class.getSimpleName();

    private OkHttpClient mOkHttpClient;

    public PhotoDownLoadNetWork(){
        mOkHttpClient = new OkHttpClient();
    }

    public boolean downPic(String url, String path){
        Log.i(TAG, "pic down url = "+ url +" ,path = " + path);
        try {
            Request request = new Request.Builder().url(url).build();
            Response response = mOkHttpClient.newCall(request).execute();

            InputStream is = null;
            byte[] buf = new byte[2048];
            int len = 0;
            FileOutputStream fos = null;
            try {
                is = response.body().byteStream();
                File file = new File(path);
                fos = new FileOutputStream(file);
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
                Log.i(TAG, "pic down success!");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "pic down fail! by write");
            } finally {
                try {
                    if (is != null){
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (fos != null){
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "pic down fail! by net");
            e.printStackTrace();
        }
        return false;
    }

}
